package com.budwk.app.sqfw.northstation.service.impl;

import com.budwk.app.sqfw.northstation.models.DeviceChannel;
import com.budwk.app.sqfw.northstation.models.NsDeviceInfo;
import com.budwk.app.sqfw.northstation.service.NsTrackrecordService;
import com.budwk.app.sqfw.northstation.service.NsdeviceinfoService;
import com.budwk.app.sys.models.Sys_area;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.app.sqfw.northstation.models.Ns_trackrecord;
import com.budwk.starter.security.utils.SecurityUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.Param;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@IocBean(args = {"refer:dao"})
public class NsTrackrecordServiceImpl extends BaseServiceImpl<Ns_trackrecord> implements NsTrackrecordService {
    public NsTrackrecordServiceImpl(Dao dao) {
        super(dao);
    }


    @Inject
    private NsTrackrecordService nsTrackrecordService;

    @Inject
    private NsdeviceinfoService nsDeviceInfoService;

    public List<DeviceChannel> getDeviceInfodb() {
        String sqlStr  = "select distinct  tb.name as manufacture,ta.device_id,longitude,latitude, on_line as  status from wvp_device_channel ta \n" +
                "left join wvp_device tb on ta.device_id= tb.device_id";;
        Sql sql = Sqls.create(sqlStr);
       // sql.setParam("code", code);
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                List<DeviceChannel> resultList = new ArrayList<DeviceChannel>();
                while (rs.next()) {
                    DeviceChannel result = new DeviceChannel();
                    for (int i = 0; i < columnCount; i++) {
                        result.setManufacture(rs.getString("manufacture"));
                        result.setDeviceId(rs.getString("device_id"));
                        result.setLongitude(rs.getString("longitude"));
                        result.setLatitude(rs.getString("latitude"));
                        result.setStatus(rs.getString("status"));
                    }
                    resultList.add(result);
                }
                return resultList;
            }
        });
        this.execute(sql);



        return sql.getList(DeviceChannel.class);
    }

    @Override
    public List<DeviceChannel> getDeviceInfo() {
        List<DeviceChannel> list = getDeviceInfodb();
//        for (DeviceChannel deviceChannel : list) {
//            Ns_trackrecord ns_trackrecord = new Ns_trackrecord();
//            String uuid = UUID.randomUUID().toString();
//            ns_trackrecord.setId(uuid);
//            ns_trackrecord.setName(deviceChannel.getManufacture());
//            ns_trackrecord.setDeviceid(deviceChannel.getDeviceId());
//            ns_trackrecord.setLongitude(deviceChannel.getLongitude());
//            ns_trackrecord.setLatitude(deviceChannel.getLatitude());
//            ns_trackrecord.setCreatedBy(SecurityUtil.getUserId());
//            nsTrackrecordService.insert(ns_trackrecord);
//        }
        return list;
    }



    //插入轨迹信息
    @Override
    public  void  installTrackrecordInfo() {
        List<DeviceChannel>  list =this.getDeviceInfodb();
        for (DeviceChannel deviceChannel : list) {
            Ns_trackrecord vo = new Ns_trackrecord();
            vo.setDeviceid(deviceChannel.getDeviceId());
            Ns_trackrecord Trackrecordinfo= Trackrecordinfo(vo);
            boolean isDistanceMoreThanOneMeter=true;
            if(Trackrecordinfo!=null) {
                installDeviceInfo(Trackrecordinfo);
                 isDistanceMoreThanOneMeter =  isDistanceMoreThanOneMeter(Double.parseDouble(Trackrecordinfo.getLatitude()), Double.parseDouble(Trackrecordinfo.getLongitude()), Double.parseDouble(deviceChannel.getLatitude()), Double.parseDouble(deviceChannel.getLongitude()));
            }
            if((Trackrecordinfo==null || isDistanceMoreThanOneMeter)&&deviceChannel.getStatus().equals("t")) {  // 这里可以写你自己的业务逻辑，比如保存到数据库，发送到消息队列等等
                Ns_trackrecord ns_trackrecord = new Ns_trackrecord();
                String uuid = UUID.randomUUID().toString();
                ns_trackrecord.setId(uuid);
                ns_trackrecord.setName(deviceChannel.getManufacture());
                ns_trackrecord.setDeviceid(deviceChannel.getDeviceId());
                ns_trackrecord.setLongitude(deviceChannel.getLongitude());
                ns_trackrecord.setLatitude(deviceChannel.getLatitude());
                //            if(SecurityUtil!=null&&SecurityUtil.getUserId()!=null)
                //            ns_trackrecord.setCreatedBy(SecurityUtil.getUserId());
                ns_trackrecord.setUserid(deviceChannel.getDeviceId());
                ns_trackrecord.setType("执法仪");
                ns_trackrecord.setUsername(deviceChannel.getManufacture());
                nsTrackrecordService.insert(ns_trackrecord);
                installDeviceInfo(ns_trackrecord);
            }

        }
    }

    //插入或更新设备信息表
    public  void installDeviceInfo(Ns_trackrecord Trackrecordinfo)
    {
        NsDeviceInfo info = new NsDeviceInfo();
        info.setDeviceid(Trackrecordinfo.getDeviceid());
        info.setName(Trackrecordinfo.getName());
        info.setType(Trackrecordinfo.getType());
        // 获取当前时间的时间戳
        long currentTimestamp = System.currentTimeMillis();
        // 判断是否超过一分钟（60000 毫秒）
        if ((currentTimestamp - Trackrecordinfo.getCreatedAt()) > 60000) {
            info.setStatus("f");
        } else {
            info.setStatus("t");
        }
        info.setLatitude(Trackrecordinfo.getLatitude());
        info.setLongitude(Trackrecordinfo.getLongitude());
        Cnd cnd = Cnd.NEW();
        if (Trackrecordinfo !=null &&Trackrecordinfo.getDeviceid() !=null && Strings.isNotBlank(Trackrecordinfo.getDeviceid().toString())) {
            cnd.and("deviceid","=",Trackrecordinfo.getDeviceid()); //根据设备id查询
        }
        List<NsDeviceInfo> list = nsDeviceInfoService.query(cnd);
        if (list.size() > 0) {
            nsDeviceInfoService.update(info);
        }else {
            nsDeviceInfoService.insertOrUpdate(info);
        }

    }

    public  Ns_trackrecord Trackrecordinfo (Ns_trackrecord bean) {
        Cnd cnd = Cnd.NEW();

        if (bean!=null && bean.getName() !=null && Strings.isNotBlank(bean.getName().toString())) {
            cnd.and("name","=",bean.getName());
        }

        if (bean!=null &&bean.getLatitude() !=null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude","=",bean.getLatitude());
        }

        if (bean!=null &&bean.getLongitude() !=null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude","=",bean.getLongitude());
        }

        if (bean!=null &&bean.getType() !=null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type","=",bean.getType());
        }

        if (bean!=null &&bean.getUsername() !=null && Strings.isNotBlank(bean.getUsername().toString())) {
            cnd.and("username","=",bean.getUsername());
        }

        if (bean!=null &&bean.getUserid() !=null && Strings.isNotBlank(bean.getUserid().toString())) {
            cnd.and("userid","=",bean.getUserid());
        }
        if (bean!=null &&bean.getCreatedAt() != null && Strings.isNotBlank(bean.getCreatedAt().toString())) {
            cnd.and("createdat", ">", bean.getCreatedAt());
        }
        if (bean !=null &&bean.getDeviceid() !=null && Strings.isNotBlank(bean.getDeviceid().toString())) {
            cnd.and("deviceid","=",bean.getDeviceid()); //根据设备id查询
        }
        cnd.orderBy("createdat", "descending");
        List <Ns_trackrecord>   list =  nsTrackrecordService.query(cnd);
        if(list.size()>0) {
            Ns_trackrecord ns_trackrecord = list.get(0);
            return ns_trackrecord;
        }
        return null;
    }



    // 地球半径（米）
    private static final double EARTH_RADIUS = 6371000;

    // 将角度转换为弧度
    private static double toRadians(double degrees) {
        return degrees * Math.PI / 180;
    }

    // 计算两个经纬度之间的距离（米）
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double lat1Rad = toRadians(lat1);
        double lon1Rad = toRadians(lon1);
        double lat2Rad = toRadians(lat2);
        double lon2Rad = toRadians(lon2);

        double deltaLat = lat2Rad - lat1Rad;
        double deltaLon = lon2Rad - lon1Rad;

        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                        Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS * c;
    }

    // 判断两个经纬度的距离是否超过一米  超过1秒才插入
    public  boolean isDistanceMoreThanOneMeter(double lat1, double lon1, double lat2, double lon2) {
        double distance = calculateDistance(lat1, lon1, lat2, lon2);
        return distance > 1;
    }


}
